package com.yazi.mxz.mobile.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.tool.CipherUtil;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.service.MemberService;
import com.yazi.mxz.mobile.jackson.filter.MemberFilter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller("memberController")
@RequestMapping("/member")
public class MemberController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(MemberController.class);
	
	@Resource
	MemberService memberService;
	
	@RequestMapping("/register")
	public String register() {
		log.debug("进入注册页面");
		return "v1.5/member_register";
	}
	
	@RequestMapping(value="/login")//,headers="!X-Requested-With"
	public String login() {
		log.debug("进入登录页面");
		return "v1.5/member_login";
	}
	
	@RequestMapping(value="/login",headers="X-Requested-With=XMLHttpRequest")
	@ResponseBody
	public int loginJson() {
		return -1;
	}
	
	@RequestMapping("/logoutDo")
	public String logoutDo() {
		Member loginMember = getMember(); 
		if (null == loginMember) {
			log.debug("注销登录: name=null");
		} else {
			log.debug("注销登录: name={}", loginMember.getName());
		}
		SecurityUtils.getSubject().logout();
		return REDIRECT_INDEX;
	}
	
	@RequestMapping("/checkName")
	@ResponseBody
	public Map<String, String> checkName(String name){
		log.debug("验证注册用户名");
		String msg = null;
		try{
			Member member = new Member();
			member.setName(name);
			List<Member> list = memberService.list(member);
			if(list.size() > 0){
				msg = "用户名已经被注册";
			}		
		}catch(Exception e){
			log.debug("验证用户名异常:", e);
			msg = e.getMessage();
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put(null == msg ? "ok":"error", msg);
		return map;
	}
	
	@RequestMapping("/registerDo/json")
	@ResponseBody
	public StatusResult registerDoJson(String captcha, Member member) {
		log.debug("提交注册");
		StatusResult jsonResult = new StatusResult();
		try {
			if (!checkCaptcha(captcha)) {
				jsonResult.setFailMessage("验证码不正确");
				return jsonResult;
			} 
			member = memberService.add(member);
			jsonResult.setOkMessage("ok");
		} catch (DataIntegrityViolationException e) {
			log.debug(e.getMessage(), e);
			jsonResult.setFailMessage("用户名已经被注册");
		} catch (MyException e) {
			log.debug(e.getMessage());
			jsonResult.setFailMessage(e.getMessage());
		} catch(Exception e) {
			log.error(e.getMessage(), e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}
	
	@RequestMapping("/loginDo/json")
	@ResponseBody
	public ObjectResult<?> loginDoJson(Member member, Boolean rememberMe, HttpServletRequest request) {
		log.debug("登录");
		ObjectResult<String> jsonResult = new ObjectResult<String>();
		try {
			login(member.getName(), rememberMe, member.getPassword());
			
			SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
			String successUrl = request.getContextPath();
			if (savedRequest != null 
					&& savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)
					&& savedRequest.getRequestUrl().indexOf("/json") == -1) {
	            successUrl = savedRequest.getRequestUrl();
	        }
			
			jsonResult.setResult(successUrl);
			jsonResult.setOkMessage("ok");
			
		} catch (AuthenticationException e) {
			jsonResult.setFailMessage("账户名或者密码错误");
		} catch(Exception e) {
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}
	
	@RequestMapping("/loginDo/code")
	public String loginDo(String code, HttpServletRequest request) {
		log.debug("token登录");
		ObjectResult<String> jsonResult = new ObjectResult<String>();
		try {
			if (null != code) {
				String key = CipherUtil.generateDESKey("dkfjie4#$%djv");
				code = code.replace("XXXX", System.lineSeparator());// TODO XXXX
				log.info("login code: {}", code);
				code = CipherUtil.DESDecrypt(code, key);
				if (null != code) {
					String[] data = code.split("\\]\\|\\[");
					// 半个小时内有效
					if (data.length == 2 && Long.parseLong(data[0]) > DateUtil.getTimeStamp() - 18e5) {
						String name = data[1];
						Member member = memberService.oneByAccountName(name);
						if (null != member) {
							login(member.getName(), true, member.getPassword());
						}
					}
				}
			}
			
		} catch(Exception e) {
			log.error("登录异常:", e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return "redirect:/user";
	}
	
	@RequestMapping("/loginfo/json")
	@ResponseBody
	public ObjectResult<?> loginfoJson() {
		log.debug("获取登录信息");
		ObjectResult<Member> jsonResult = new ObjectResult<Member>();
		jsonResult.setFilter(MemberFilter.get4Loginfo());
		try {
			jsonResult.setResult(getMember());
			jsonResult.setOk();
		} catch(Exception e) {
			log.error(e.getMessage(), e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}
	
	private void login(String name, boolean rememberMe, String password) {
		UsernamePasswordToken token = new UsernamePasswordToken();
		token.setUsername(name);
		token.setPassword(password.toCharArray());
		token.setRememberMe(rememberMe);// 记住用户
		Subject subject = SecurityUtils.getSubject();
		subject.login(token);
	}
	
}
